package mz.matafe.bolao

/**
 * Domain Class for a Bet.
 *
 * <p>Represents a bet. Eg.: (Match 1 0x0)
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class Bet implements Comparable{

    //services
    def authenticateService

    //properties
    Match match
    Integer score1
    Integer score2
    Date dateCreated
    Date lastUpdated

    static belongsTo = [user:User]

    static constraints = {
        match(unique:'user')
        score1(validator: {val, obj ->
                if (val == '' || val == 0) {
                    obj.score1 = 0
                    return true
                } else if (val < 1) {
                    return false;
                }
            })
        score2(validator: {val, obj ->
                if (val == '' || val == 0) {
                    obj.score2 = 0
                    return true
                } else if (val < 1) {
                    return false;
                }
            })
        dateCreated()
        lastUpdated()
        user(nullable: true)//try to put not null!
    }

    static mapping = {
        table 'WC_BET'
    }

    def beforeInsert = {
        def loggedUser = authenticateService.userDomain()
        this.user = this.user ?: loggedUser
    }

    def afterInsert = {
        log.info "Bet ${id} inserted"
    }

    String toString(){
        "${this.class.name}:id[$id];user[$user];match[$match]"
    }

    int compareTo(Object o){
        this.id <=> ((Bet)o).id
    }

}
